package com.hospital.wx.controller;

import com.hospital.wx.common.CommonResult;
import com.hospital.wx.controller.form.QrcodeRequestDTO;
import com.hospital.wx.service.PatientVisitsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/patient/visits")
@Slf4j
@Tag(name = "PatientVisitsController", description = "问诊记录管理接口")
public class PatientVisitsController {

    @Autowired
    private PatientVisitsService patientVisitsService;

    @GetMapping("/selectAll")
    @Operation(summary = "查询所有问诊记录")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
    public CommonResult selectAll() {
        try {
            ArrayList<HashMap> list = patientVisitsService.selectAll();
            return CommonResult.ok().put(CommonResult.RETURN_RESULT, list);
        } catch (Exception e) {
            log.error("查询出现错误", e);
            return CommonResult.failed("查询出现错误");
        }
    }

    @PostMapping("/export")
    @Operation(summary = "导出就诊记录")
    public ResponseEntity<byte[]> exportVisitRecord(@RequestParam Integer patientId,
                                                    @RequestParam(defaultValue = "pdf") String exportType) {
        try {
            byte[] fileContent = patientVisitsService.generateVisitReport(patientId, exportType);
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String filename = URLEncoder.encode("就诊记录.pdf", "UTF-8");
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDisposition(ContentDisposition.builder("attachment")
                    .filename(filename)
                    .build());
            headers.setCacheControl("no-cache");
            headers.setPragma("no-cache");

            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出就诊记录失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出就诊记录")
    public ResponseEntity<byte[]> exportVisitRecord02(
            @RequestParam Integer patientId,
            @RequestParam(defaultValue = "pdf") String exportType) {
        try {
            byte[] fileContent = patientVisitsService.generateVisitReport(patientId, exportType);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String filename = URLEncoder.encode("就诊记录.pdf", "UTF-8");

            // 设置更完整的响应头
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDisposition(ContentDisposition.builder("attachment")
                    .filename(filename)
                    .build());
            // 添加缓存控制头
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0L);
            // 添加文件大小
            headers.setContentLength(fileContent.length);

            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出就诊记录失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/share-image")
    @Operation(summary = "生成分享图片")
    public CommonResult generateShareImage(@RequestParam Integer visitId) {
        try {
            String shareImage = patientVisitsService.generateShareImage(visitId);
            if (shareImage == null) {
                return CommonResult.failed("生成图片失败");
            }
            return CommonResult.ok().put(CommonResult.RETURN_RESULT, shareImage);
        } catch (Exception e) {
            log.error("生成图片过程中出现异常", e);
            return CommonResult.failed("生成图片过程中出现异常");
        }
    }


    @PostMapping("/qrcode")
    @Operation(summary = "生成二维码")
    public CommonResult generateQrcode(@Valid @RequestBody QrcodeRequestDTO request) {
//        Map<String, Object> response = new HashMap<>();

        try {
            String base64Qrcode = patientVisitsService.generateAndCacheQrcode(
                    request.getPage(),
                    request.getScene(),
                    request.getWidth()
            );
//            String qrcodeUrl = patientVisitsService.generateQrcode(request.getVisitId(), request.getPage());
//            response.put("qrcodeUrl", qrcodeUrl);
            return CommonResult.ok().put("result", base64Qrcode);
        } catch (Exception e) {
            log.error("生成二维码失败", e);
            return CommonResult.failed("生成二维码失败");
        }
    }



}

